package dao

import (
	"fmt"
	"system-admin/internal/models"
	"system-admin/internal/utils"
	"time"
)

// 创建用户初始化结构体对象
func NewUserObject() (user *models.User) {
	user = &models.User{}
	return
}

// 新增用户
func InsertUser(username string, password string, fullname string) {
	db := utils.GetDB()
	user := NewUserObject()
	user.Username = username //创建账户
	user.Password = password //创建密码
	user.Fullname = fullname //用户名称
	user.Money = 100         //初始金钱
	user.Level = 1           //初始等级
	user.BlogAmount = 0      //初始文章数量
	user.ThumbUpAmount = 0   //初始点赞数量
	user.CollectAmount = 0   //初始收藏数量

	db.Create(&user)
}

// 根据用户名查询用户是否存在
func QueryUserByUsername(username string) (result bool) {
	db := utils.GetDB()
	userModel := NewUserObject()
	queryResult := db.Table("users").First(&userModel, "username = ?", username)

	//获取到的条数，如果能查询到，条数只能是1，如果没查到则0
	row := queryResult.RowsAffected
	if row == 1 {
		//成功查询
		result = true
	} else {
		//查询不到
		result = false
	}
	return
}

// 查询用户账号和密码是否匹配（登录专用）
func QueryUsernameAndPassword(username string, password string) (result bool) {
	db := utils.GetDB()
	user := &models.User{}
	queryResult := db.Table("users").Where("username = ? AND password = ?", username, password).First(&user)

	//更新token
	str := fmt.Sprintf("%d", time.Now().Unix())
	temp := utils.MD5Encode(str)
	db.Table("users").Where("username = ? AND password = ?", username, password).Update("identity", temp)

	row := queryResult.RowsAffected
	if row == 1 {
		//成功查询
		result = true
	} else {
		//查询不到
		result = false
	}
	return
}

// 查询前X个用户数据并根据等级来排名
func QueryUserByLimitAndOrderByLevel(limitQuantity int) (userList *models.UserList, result bool, row int) {
	db := utils.GetDB()
	userList = &models.UserList{}

	queryResult := db.Order("level").Limit(limitQuantity).Find(&userList.User)

	row = int(queryResult.RowsAffected)
	if row != 0 {
		//成功查询
		result = true
	} else {
		//查询不到
		result = false
	}
	return
}
